<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\facade\Db;
use think\facade\Cookie;
use think\facade\Cache;
use think\captcha\facade\Captcha;

use app\common\model\Category as CategoryModel;
use app\common\model\Users as UsersModel;
use app\common\model\Sms as SmsModel;
use app\common\model\Message as MessageModel;
use app\common\model\Order as OrderModel;
use app\common\model\Lists as ListsModel;
use app\common\model\Region as RegionModel;

use app\admin\validate\Users as validateUsers;

/**
 * @title 用户管理
 * @description 用户登录注册，个人中心
 * //@group 接口分组
 * //@header name:key require:1 default: desc:秘钥(区别设置)
 * //@param name:public type:int require:1 default:1 other: desc:公共参数(区别设置)
 */
class Login extends Base
{

    private $appid = 'wx30cb475cb02b6294';
    private $secret = '7b5eba7d492f470cd427bb59726fc908';

    private $user=[];

    function __construct(){
        parent::__construct();
//        $param = input('param.');
//        $token = isset($param['token'])?$param['token']:'';
//        if($token) {
//            $res = checkToken($param['token']);
//            if ($res['code']==2) {
//                return dyajaxReturn(-1, $res['msg']);
//            }
//            $this->user = json_decode($res['data'], true);
//        }
    }

    /**
//     * @title 获取图形验证码
//     * @description 接口说明：获取图形验证码
//     * @author 开发者 唐寅
//     * @url /api/Users/vertify
//     * @method GET POST
     *
     */
    public function vertify(){
        return Captcha::create('verify');
    }


    /**
//     * @title 用户注册
//     * @description 接口说明：用户注册
//     * @author 开发者 唐寅
//     * @url /api/Users/register
//     * @method GET POST
//     *
//     * @param name:registermobile type:varchar require:1 default:0 other: desc:手机号
//     * @param name:password type:varchar require:1 default:0 other: desc:密码
//     * @param name:vertify type:int require:1 default:1 other: desc:图形验证码
//     * @param name:code type:int require:1 default:1 other: desc:短信验证码
     *
     */
    public function register(){

        $param = input('param.');

        $validate = new validateUsers();
        $result = $validate->scene('register')->batch(false)->check($param);
        if(!$result){
            return dyajaxReturn(0,$validate->getError());
        }

        $vertify = $param['vertify'];
        if( !captcha_check($vertify)) {
            return dyajaxReturn(0,'图形验证码错误');
        }

        //验证短信验证码
        $SmsModel = new SmsModel();
        $is_sms = $SmsModel ->checkSmsCode($param['registermobile'],$param['code'],'register');
        if(!$is_sms['code']){
            return dyajaxReturn(0,$is_sms['msg']);
        }

        $model = new UsersModel();
        $res = $model -> handle($param);
        return dyajaxReturn($res['code'],$res['msg']);

    }

    /**
//     * @title 微信用户登录
//     * @description 接口说明：type字段：默认为getuserinfo，用户授权登录，getPhoneNumber为手机号授权
//     * @author 开发者 唐寅
//     * @url /api/Users/login
//     * @method GET POST
//     *
//     * @param name:type type:varchar require:1 default:0 other: desc:getuserinfo,getPhoneNumber
//     * @param name:code type:varchar require:1 default:0 other: desc:微信端code
//     * @param name:iv type:varchar require:1 default:0 other: desc:iv字段
//     * @param name:encryptedData type:varchar require:1 default:0 other: encryptedData字段
     *
     */
    public function login()
    {
        $param = input('param.');
        if(!isset($param['code']) || $param['code'] == ''){
            return dyajaxReturn(0,'code值不能为空');
        }
        if(!isset($param['iv']) || $param['iv'] == ''){
            return dyajaxReturn(0,'iv值不能为空');
        }
        if(!isset($param['encryptedData']) || $param['encryptedData'] == ''){
            return dyajaxReturn(0,'encryptedData值不能为空');
        }

        $type = isset($param['type'])?$param['type']:'getuserinfo';
        $code = $param['code'];

        if($code){
            $appid = $this->appid;
            $secret = $this->secret;
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
            $result = curlGet($url);
            $res = json_decode($result, true);
//            return dyajaxReturn(1,'返回',$res);
            $openid = $res['openid'];
            $session_key = $res['session_key'];
            $unionid = isset($res['unionid'])?$res['unionid']:'';

            $iv = $param['iv'];
            $encryptedData = $param['encryptedData'];

            $UsersModel = new UsersModel();
            $oauth_user = DB::name('users')->where('openid', $openid)->find();
            //不存在则添加
            if (!isset($oauth_user['id'])) {
                Db::startTrans();
                try {
                    $u['act'] = 'add';
                    $u['openid'] = $openid;
                    $u['name'] = 'wx_'.rand(10000,99999);
                    $user_res = $UsersModel->handle($u);
                    if(!$user_res['code']){
                        Db::rollback();
                        return dyajaxReturn(0,$user_res['msg']);
                    }
                    $user_id = $user_res['data'];
                    $data['user_id'] = $user_id;
                    $data['session_key'] = $session_key;
                    $data['openid'] = $openid;
                    $data['unionid'] = $unionid;
                    $data['oauth'] = 'weixin';
                    $oauth_id =DB::name('oauth_users')->insertGetId($data);
                    if(!$oauth_id){
                        Db::rollback();
                        return dyajaxReturn(0,'授权失败');
                    }
                    //保存房间信息
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return dyajaxReturn(0, $e->getMessage());
                }
            }else{
                $user_id = $oauth_user['id'];
                //存在看看有没有user_id 不存在则创建
                if(!isset($oauth_user['id'])){
                    $u['act'] = 'add';
                    $u['openid'] = $openid;
                    $u['name'] = 'wx_'.rand(10000,99999);
                    $user_res = $UsersModel->handle($u);
                    if(!$user_res['code']){
                        return dyajaxReturn(0,$user_res['msg']);
                    }
//                    $user_id = $user_res['data'];
//                    DB::name('oauth_users')->where('tu_id','=',$oauth_id)->update([
//                       'user_id'=>$user_id
//                    ]);
                }
            }

            //手机授权
            if($type == 'getPhoneNumber') {
                $userData_res = $this->getUserData($encryptedData,$iv,$session_key);
                $userData = json_decode($userData_res,true);
                $mobile = $userData['phoneNumber'];

                $user = $UsersModel->where('mobile','=',$mobile)->find();
                if($user['id']){
                    //存在则把刚才生成用户删掉，并用查到的用户代替
                    $UsersModel->where('id','=',$user_id)->delete();

                    $is_up = $UsersModel->where('id','=',$user['id'])->update([
                        'openid'=>$openid,
                        'update_time'=>time()
                    ]);
                    if(!$is_up){
                        return dyajaxReturn(0,'授权手机失败1');
                    }
                    $user_id = $user['id'];
                    DB::name('oauth_users')->where('tu_id','=',$oauth_id)->update([
                        'user_id'=>$user_id
                    ]);
                }else{
                    //不存在则添加用户id
                    $is_up = $UsersModel->where('id','=',$user_id)->update([
                        'mobile'=>$mobile,
                        'update_time'=>time()
                    ]);
                    if(!$is_up){
                        return dyajaxReturn(0,'授权手机失败2');
                    }
                }
            }

            //登录
            $user_res = $UsersModel ->wxLogin($user_id);
            if(!$user_res['code']){
                return dyajaxReturn(0,$user_res['msg']);
            }

            $return['openid'] = $openid;
            $return['session_key'] = $session_key;
            $return['unionid'] = $unionid;
//            $return['oauth_id'] = $oauth_id;
            $return['token'] = $user_res['data']['token'];
            $return['mobile'] = $user_res['data']['mobile'];
            $return['user_info'] = $user_res['data'];

            return dyajaxReturn(1,'返回',$return);

        }

    }



    public function getPhone(){
        $param = input("param.");

        if(!isset($param['iv']) || $param['iv'] == ''){
            return dyajaxReturn(0,'iv值不能为空');
        }
        if(!isset($param['encryptedData']) || $param['encryptedData'] == ''){
            return dyajaxReturn(0,'encryptedData值不能为空');
        }
        if(!isset($param['openid']) || $param['openid'] == ''){
            return dyajaxReturn(0,'openid值不能为空');
        }
        if(!isset($param['session_key']) || $param['session_key'] == ''){
            return dyajaxReturn(0,'session_key值不能为空');
        }

        $openid = $param['openid'];
        $encryptedData = $param['encryptedData'];
        $iv = $param['iv'];
        $session_key = $param['session_key'];

        $userData_res = $this->getUserData($encryptedData,$iv,$session_key);
        $userData = json_decode($userData_res,true);
        $mobile = $userData['phoneNumber'];

        $UsersModel = new UsersModel();
        $is_up = $UsersModel->where('openid','=',$openid)->update([
            'mobile'=>$mobile,
            'update_time'=>time()
        ]);
        if(!$is_up){
            return dyajaxReturn(0,'授权手机失败');
        }
        $info = $UsersModel->where('openid','=',$openid)->find();
        return dyajaxReturn(1,'授权手机成功',$info);

    }


    public function getUserData($encryptedData,$iv,$session_key)
    {
        $aesKey=base64_decode($session_key);
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $res=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        return $res;
    }



    /**
     * @title 微信手机号登录
     * @description
     * @author 唐寅
     * @url /api/Users/getPhoneTrue
     * @method GET POST
     * @param name:code type:String require:1 default:'' other: desc:手机号code
     */
    public function getPhoneTrue(){
        $param = input("param.");
        if(!isset($param['code']) || $param['code'] == ''){
            return dyajaxReturn(0,'code值不能为空');
        }
//        if(!isset($param['unionid']) || $param['unionid'] == ''){
//            return dyajaxReturn(0,'unionid值不能为空');
//        }
        //$unionid = $param['unionid'];
        $code = $param['code'];

        $appid = $this->appid;
        $secret = $this->secret;

//        $at_res = $this->GetAccessToken($appid,$secret);
//        $access_token = $at_res['access_token'];
        if(Cache::get("access_token")){
            $access_token = Cache::get("access_token");
        }else {
            $at_res = $this->GetAccessToken($appid,$secret);
            $access_token = $at_res['access_token'];
            Cache::set("access_token", $at_res['access_token'], 1000);
        }

        $result = $this->getPhoneTwo($code,$access_token);
        $result = json_decode($result,true);

        if($result['errcode'] == 0) {
            $phone = $result['phone_info']['phoneNumber'];
            $UsersModel = new UsersModel();
            //查unionid
//            $u = $UsersModel -> where('unionid','=',$unionid)->find();
//            if(!$u['id']){
                //查手机号
                $u2 = $UsersModel -> where('mobile','=',$phone)->find();
                if(!isset($u2['id'])){
                    //不存在就注册
                    $param['act'] = 'add';
                    $param['mobile'] = $phone;
                    $res = $UsersModel->handle($param);
                    if($res['code'] == 0){
                        return dyajaxReturn(0,$res['msg']);
                    }
                    $user_id = $res['data'];
                }else{
                    $user_id = $u2['id'];
                }
//            }else{
//                $user_id = $u['id'];
//            }
            //登录
            $user_res = $UsersModel ->wxLogin($user_id);
            if(!$user_res['code']){
                return dyajaxReturn(0,$user_res['msg']);
            }

            $return['token'] = $user_res['data']['token'];
            $return['mobile'] = $user_res['data']['mobile'];
            $return['user_info'] = $user_res['data'];

            return dyajaxReturn(1,'授权登录成功',$return);
        }else{
            return dyajaxReturn(0,'获取手机号码失败');
        }
    }


    public function GetAccessToken($appid,$secret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);//运行curl，结果以json形式返回
        $data = json_decode($res,true);
        curl_close($ch);
        return $data;
    }


    public function getPhoneTwo($code,$access_token){
        $arr = [
            "code"=>$code
        ];
        $header = array('Content-Type: application/json');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $res = curlPost($url,$arr,5,$header,'json');
        return $res;
    }



    /**
     * @title 获取Openid
     * @description 获取Openid
     * @author 开发者 唐寅
     * @url /api/Users/getOpenid
     * @method GET POST
     *
     * @param name:code type:varchar require:1 default:0 other: desc:code
     *
     */
    public function getOpenid(){
        $param = input("param.");
        if(!isset($param['code']) || $param['code'] == ''){
            return dyajaxReturn(0,'code值不能为空');
        }
        $code = $param['code'];

        $appid = $this->appid;
        $secret = $this->secret;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $result = curlGet($url);
        $res = json_decode($result, true);
        $openid = $res['openid'];
        $session_key = $res['session_key'];

        $arr['openid'] = $openid;
        $arr['session_key'] = $session_key;
        $unionid = isset($res['unionid'])?$res['unionid']:'';
        $arr['unionid'] = $unionid;

        return dyajaxReturn(1,'获取成功',$arr);

    }

    public function pwdLogin(){
        $param = input("param.");
        if(!isset($param['mobile']) && $param['mobile'] == "" ){
            return dyajaxReturn(0,'手机号不能为空');
        }
        if(!isset($param['password']) && $param['password'] == "" ){
            return dyajaxReturn(0,'密码不能为空');
        }
        $model = new UsersModel();
        $res = $model->login($param['mobile'],$param['password'],$param['type']);
        return dyajaxReturn($res['code'],$res['msg'],$res['data']);
    }
}
